package com.liuh.fram.util;

import java.io.IOException;
import java.security.MessageDigest;

import com.jfinal.kit.PropKit;
import com.liuh.fram.io.CompressTools;
import com.liuh.fram.io.ZLibTools;
import com.liuh.fram.log.Log4jLogExtra;

/**
 * @note 加密工具类
 * @author liuh
 * */
public class EncryptKit {

	static Log4jLogExtra log4jExtra = new Log4jLogExtra(EncryptKit.class);

	/**
	 * @note MD5 加密
	 * @author liuh
	 * */
	public static String MD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * @note 压缩数据
	 * @author liuh
	 * @throws AppException
	 * */
	public static String compress_base64(String inputVal) throws Exception {
		CompressTools gzipTools = new ZLibTools();
		String com_str = gzipTools.compressBase64(inputVal);
		boolean is_dev = PropKit.getBoolean("devMode");
		if (is_dev) {
			log4jExtra.debug("压缩及编码前：" + inputVal + "\n压缩前大小："
					+ inputVal.length());
			log4jExtra.debug("压缩及编码后：" + com_str + "\n压缩后大小："
					+ com_str.length());
		}
		return com_str;
	}

	/**
	 * @note 解压数据
	 * @author liuh
	 * @throws AppException
	 * @throws IOException
	 * */
	public static String deCompress_base64(String inputVal) throws Exception {
		CompressTools gzipTools = new ZLibTools();
		String decom_str = gzipTools.decompressBase64(inputVal);
		boolean is_dev = PropKit.getBoolean("devMode");
		if (is_dev) {
			log4jExtra.debug("解压及编码前：" + inputVal + "\n解码前大小："
					+ inputVal.length());
			log4jExtra.debug("解压及编码后：" + decom_str + "\n解码后大小："
					+ decom_str.length());
		}
		return decom_str;
	}

	public static void main(String[] args) {
		System.out.println(EncryptKit.MD5("liuhui"));
		// E10ADC3949BA59ABBE56E057F20F883E
		// E10ADC3949BA59ABBE56E057F20F883E

	}
}